package com.mall.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.user.common.exception.BusinessException;
import com.mall.user.common.response.ResultCode;
import com.mall.user.constant.CommonConstant;
import com.mall.user.model.dto.favorite.UserFavoriteQueryRequest;
import com.mall.user.model.entity.UserFavorite;
import com.mall.user.model.vo.UserFavoriteVO;
import com.mall.user.service.UserFavoriteService;
import com.mall.user.mapper.UserFavoriteMapper;
import com.mall.user.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 张云博
* @description 针对表【user_favorite(用户收藏表)】的数据库操作Service实现
* @createDate 2025-08-29 10:04:36
*/
@Slf4j
@Service
public class UserFavoriteServiceImpl extends ServiceImpl<UserFavoriteMapper, UserFavorite>
    implements UserFavoriteService{

    @Override
    @Transactional
    public Long addFavorite(Long userId, Long productId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (productId == null || productId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "商品ID不能为空");
        }

        // 检查是否已收藏
        if (isFavorite(userId, productId)) {
            throw new BusinessException(ResultCode.FAILED, "该商品已收藏");
        }

        // 创建收藏记录
        UserFavorite userFavorite = new UserFavorite();
        userFavorite.setUser_id(userId);
        userFavorite.setProduct_id(productId);
        userFavorite.setCreated_time(LocalDateTime.now());

        boolean result = this.save(userFavorite);
        if (!result) {
            throw new BusinessException(ResultCode.SYSTEM_ERROR, "收藏失败");
        }

        log.info("用户 {} 收藏商品 {} 成功", userId, productId);
        return userFavorite.getId();
    }

    @Override
    @Transactional
    public boolean removeFavorite(Long userId, Long productId) {
        // 参数校验
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }
        if (productId == null || productId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "商品ID不能为空");
        }

        // 构建删除条件
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);

        boolean result = this.remove(queryWrapper);
        if (result) {
            log.info("用户 {} 取消收藏商品 {} 成功", userId, productId);
        }
        return result;
    }

    @Override
    public boolean isFavorite(Long userId, Long productId) {
        if (userId == null || userId <= 0 || productId == null || productId <= 0) {
            return false;
        }

        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .eq("product_id", productId);

        return this.count(queryWrapper) > 0;
    }

    @Override
    public Page<UserFavoriteVO> getUserFavorites(Long userId, int current, int pageSize) {
        if (userId == null || userId <= 0) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "用户ID不能为空");
        }

        // 构建查询条件
        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId)
                   .orderByDesc("created_time");

        // 分页查询
        Page<UserFavorite> page = new Page<>(current, pageSize);
        Page<UserFavorite> favoriteePage = this.page(page, queryWrapper);

        // 转换为VO
        Page<UserFavoriteVO> voPage = new Page<>(current, pageSize, favoriteePage.getTotal());
        List<UserFavoriteVO> voList = getUserFavoriteVO(favoriteePage.getRecords());
        voPage.setRecords(voList);

        return voPage;
    }

    @Override
    public QueryWrapper<UserFavorite> getQueryWrapper(UserFavoriteQueryRequest userFavoriteQueryRequest) {
        if (userFavoriteQueryRequest == null) {
            throw new BusinessException(ResultCode.PARAMS_ERROR, "请求参数为空");
        }

        Long id = userFavoriteQueryRequest.getId();
        Long userId = userFavoriteQueryRequest.getUserId();
        Long productId = userFavoriteQueryRequest.getProductId();
        LocalDateTime createdTime = userFavoriteQueryRequest.getCreatedTime();
        String sortField = userFavoriteQueryRequest.getSortField();
        String sortOrder = userFavoriteQueryRequest.getSortOrder();

        QueryWrapper<UserFavorite> queryWrapper = new QueryWrapper<>();

        // 精确查询条件
        queryWrapper.eq(id != null, "id", id);
        queryWrapper.eq(userId != null, "user_id", userId);
        queryWrapper.eq(productId != null, "product_id", productId);

        // 时间查询（精确匹配或按日期查询）
        queryWrapper.eq(createdTime != null, "created_time", createdTime);

        // 排序条件
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), 
                           sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);

        return queryWrapper;
    }

    @Override
    public UserFavoriteVO getUserFavoriteVO(UserFavorite userFavorite) {
        if (userFavorite == null) {
            return null;
        }

        UserFavoriteVO userFavoriteVO = new UserFavoriteVO();
        BeanUtils.copyProperties(userFavorite, userFavoriteVO);
        
        // 处理字段名映射
        userFavoriteVO.setUserId(userFavorite.getUser_id());
        userFavoriteVO.setProductId(userFavorite.getProduct_id());
        userFavoriteVO.setCreatedTime(userFavorite.getCreated_time());
        
        return userFavoriteVO;
    }

    @Override
    public List<UserFavoriteVO> getUserFavoriteVO(List<UserFavorite> userFavoriteList) {
        if (userFavoriteList == null || userFavoriteList.isEmpty()) {
            return List.of();
        }

        return userFavoriteList.stream()
                .map(this::getUserFavoriteVO)
                .collect(Collectors.toList());
    }

    @Override
    public Long getTotalFavoriteCount() {
        return this.count();
    }

    @Override
    public Long getTodayFavoriteCount() {
        LocalDateTime todayStart = LocalDate.now().atStartOfDay();
        QueryWrapper<UserFavorite> query = new QueryWrapper<>();
        query.ge("created_time", todayStart);
        return this.count(query);
    }
}




